<template>
  <div class="order-detail">
    <!-- 面包屑导航 -->
    <div class="breadcrumb">
      <div class="container">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item :to="{ path: '/orders' }">我的订单</el-breadcrumb-item>
          <el-breadcrumb-item>订单详情</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </div>

    <div class="container" v-loading="loading">
      <div v-if="order" class="order-content">
        <!-- 订单状态 -->
        <div class="order-status-card">
          <div class="status-info">
            <div class="status-text">
              <h2>{{ getStatusText(order.orderStatus) }}</h2>
              <p v-if="order.orderStatus === OrderStatus.PENDING_PAYMENT">
                请在 {{ getPaymentTimeLeft() }} 内完成支付，超时订单将自动取消
              </p>
              <p v-else-if="order.orderStatus === OrderStatus.PENDING_RECEIPT">
                商品已发货，请注意查收
              </p>
            </div>
          </div>
          <div class="order-actions">
            <el-button
              v-if="order.orderStatus === OrderStatus.PENDING_PAYMENT"
              type="primary"
              size="large"
              @click="payOrder"
            >
              立即支付
            </el-button>
            <el-button
              v-if="order.orderStatus === OrderStatus.PENDING_PAYMENT"
              size="large"
              @click="cancelOrder"
            >
              取消订单
            </el-button>
            <el-button
              v-if="order.orderStatus === OrderStatus.PENDING_RECEIPT"
              type="success"
              size="large"
              @click="confirmOrder"
            >
              确认收货
            </el-button>
          </div>
        </div>

        <!-- 收货信息 -->
        <div class="info-card">
          <h3>收货信息</h3>
          <div class="address-info">
            <div class="address-item">
              <span class="label">收货人：</span>
              <span>{{ order.consigneeName }}</span>
            </div>
            <div class="address-item">
              <span class="label">联系电话：</span>
              <span>{{ order.consigneePhone }}</span>
            </div>
            <div class="address-item">
              <span class="label">收货地址：</span>
              <span>{{ order.consigneeAddress }}</span>
            </div>
          </div>
        </div>

        <!-- 商品信息 -->
        <div class="info-card">
          <h3>商品信息</h3>
          <div class="goods-list">
            <div v-for="item in order.items" :key="item.id" class="goods-item">
              <div class="goods-image">
                <img :src="item.productImage || '/placeholder.svg'" :alt="item.productName" />
              </div>
              <div class="goods-info">
                <h4>{{ item.productName }}</h4>
                <p v-if="item.skuSpecifications" class="goods-spec">
                  {{ formatSpecifications(item.skuSpecifications) }}
                </p>
                <div class="goods-price">
                  <span class="price">¥{{ item.price }}</span>
                  <span class="quantity">x{{ item.quantity }}</span>
                </div>
              </div>
              <div class="goods-total">
                ¥{{ item.totalAmount }}
              </div>
            </div>
          </div>
        </div>

        <!-- 订单信息 -->
        <div class="info-card">
          <h3>订单信息</h3>
          <div class="order-info">
            <div class="info-row">
              <span class="label">订单编号：</span>
              <span>{{ order.orderNo }}</span>
            </div>
            <div class="info-row">
              <span class="label">下单时间：</span>
              <span>{{ formatDate(order.createdAt) }}</span>
            </div>
            <div class="info-row" v-if="order.paymentTime">
              <span class="label">支付时间：</span>
              <span>{{ formatDate(order.paymentTime) }}</span>
            </div>
            <div class="info-row" v-if="order.shippingTime">
              <span class="label">发货时间：</span>
              <span>{{ formatDate(order.shippingTime) }}</span>
            </div>
            <div class="info-row" v-if="order.confirmTime">
              <span class="label">确认收货时间：</span>
              <span>{{ formatDate(order.confirmTime) }}</span>
            </div>
            <div class="info-row" v-if="order.deliveryCompany && order.deliveryNo">
              <span class="label">物流信息：</span>
              <span>{{ order.deliveryCompany }} {{ order.deliveryNo }}</span>
            </div>
            <div class="info-row" v-if="order.buyerMessage">
              <span class="label">买家留言：</span>
              <span>{{ order.buyerMessage }}</span>
            </div>
          </div>
        </div>

        <!-- 费用明细 -->
        <div class="info-card">
          <h3>费用明细</h3>
          <div class="amount-detail">
            <div class="amount-row">
              <span>商品总额：</span>
              <span>¥{{ order.goodsAmount }}</span>
            </div>
            <div class="amount-row">
              <span>运费：</span>
              <span>¥{{ order.shippingFee }}</span>
            </div>
            <div class="amount-row" v-if="order.pointsAmount > 0">
              <span>积分抵扣：</span>
              <span class="discount">-¥{{ order.pointsAmount }}</span>
            </div>
            <div class="amount-row total">
              <span>实付款：</span>
              <span class="total-amount">¥{{ order.totalAmount }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 订单不存在 -->
      <div v-else-if="!loading" class="order-not-found">
        <el-empty description="订单不存在或已被删除">
          <el-button type="primary" @click="$router.push('/orders')">
            返回订单列表
          </el-button>
        </el-empty>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'

import { useOrderStore } from '@/stores/order'
import { OrderStatus, PaymentStatus, type Order } from '@/api/order'

const route = useRoute()
const router = useRouter()
const orderStore = useOrderStore()

const loading = ref(false)
const order = ref<Order | null>(null)

const orderId = computed(() => parseInt(route.params.id as string))

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 格式化规格
const formatSpecifications = (specs: Record<string, unknown>) => {
  if (!specs || typeof specs !== 'object') return ''
  return Object.entries(specs).map(([key, value]) => `${key}: ${value}`).join(', ')
}

// 获取状态文本
const getStatusText = (status: OrderStatus) => {
  const statusMap = {
    [OrderStatus.PENDING_PAYMENT]: '等待买家付款',
    [OrderStatus.PENDING_SHIPMENT]: '等待卖家发货',
    [OrderStatus.PENDING_RECEIPT]: '等待买家收货',
    [OrderStatus.COMPLETED]: '交易成功',
    [OrderStatus.CANCELLED]: '交易关闭',
    [OrderStatus.REFUNDING]: '退款中'
  }
  return statusMap[status] || '未知状态'
}

// 获取状态图标
const getStatusIcon = (status: OrderStatus) => {
  const iconMap = {
    [OrderStatus.PENDING_PAYMENT]: '⏰',
    [OrderStatus.PENDING_SHIPMENT]: '📦',
    [OrderStatus.PENDING_RECEIPT]: '🚚',
    [OrderStatus.COMPLETED]: '✅',
    [OrderStatus.CANCELLED]: '❌',
    [OrderStatus.REFUNDING]: '⚠️'
  }
  return iconMap[status] || '⏰'
}

// 获取状态图标样式类
const getStatusIconClass = (status: OrderStatus) => {
  const classMap = {
    [OrderStatus.PENDING_PAYMENT]: 'warning',
    [OrderStatus.PENDING_SHIPMENT]: 'info',
    [OrderStatus.PENDING_RECEIPT]: 'primary',
    [OrderStatus.COMPLETED]: 'success',
    [OrderStatus.CANCELLED]: 'danger',
    [OrderStatus.REFUNDING]: 'warning'
  }
  return classMap[status] || 'info'
}

// 获取支付剩余时间
const getPaymentTimeLeft = () => {
  if (!order.value) return ''
  const createdTime = new Date(order.value.createdAt).getTime()
  const now = Date.now()
  const timeLeft = createdTime + (24 * 60 * 60 * 1000) - now // 24小时后过期

  if (timeLeft <= 0) return '已过期'

  const hours = Math.floor(timeLeft / (60 * 60 * 1000))
  const minutes = Math.floor((timeLeft % (60 * 60 * 1000)) / (60 * 1000))

  return `${hours}小时${minutes}分钟`
}

// 获取订单详情
const fetchOrderDetail = async () => {
  try {
    loading.value = true
    order.value = await orderStore.fetchOrderById(orderId.value)
  } catch (error) {
    console.error('获取订单详情失败:', error)
    ElMessage.error('获取订单详情失败')
  } finally {
    loading.value = false
  }
}

// 支付订单
const payOrder = () => {
  if (!order.value) {
    ElMessage.error('订单信息不存在')
    return
  }

  // 检查订单状态
  if (order.value.orderStatus !== OrderStatus.PENDING_PAYMENT) {
    ElMessage.error('当前订单状态不允许支付')
    return
  }

  // 检查支付状态
  if (order.value.paymentStatus === PaymentStatus.PAID) {
    ElMessage.warning('订单已支付，无需重复支付')
    return
  }

  // 跳转到支付页面
  ElMessage.info('正在跳转到支付页面...')
  router.push(`/order/pay/${orderId.value}`)
}

// 取消订单
const cancelOrder = async () => {
  try {
    await ElMessageBox.confirm('确认取消订单？取消后无法恢复', '提示', {
      confirmButtonText: '确认取消',
      cancelButtonText: '继续支付',
      type: 'warning'
    })

    await orderStore.cancelOrder(orderId.value)
    ElMessage.success('订单已取消')

    // 刷新订单详情
    await fetchOrderDetail()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消订单失败:', error)
      ElMessage.error('取消订单失败')
    }
  }
}

// 确认收货
const confirmOrder = async () => {
  try {
    await ElMessageBox.confirm('确认收货？确认后订单将完成', '提示', {
      confirmButtonText: '确认收货',
      cancelButtonText: '取消',
      type: 'info'
    })

    await orderStore.confirmOrder(orderId.value)
    ElMessage.success('确认收货成功')

    // 刷新订单详情
    await fetchOrderDetail()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('确认收货失败:', error)
      ElMessage.error('确认收货失败')
    }
  }
}

onMounted(() => {
  fetchOrderDetail()
})
</script>

<style scoped>
.order-detail {
  min-height: 100vh;
  background: #f5f5f5;
}

.breadcrumb {
  background: white;
  padding: 15px 0;
  border-bottom: 1px solid #e0e0e0;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.order-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* 订单状态卡片 */
.order-status-card {
  background: white;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.status-info {
  display: flex;
  align-items: center;
  gap: 20px;
}

.status-icon {
  font-size: 48px;
}

.status-icon.warning {
  color: #e6a23c;
}

.status-icon.info {
  color: #909399;
}

.status-icon.primary {
  color: #409eff;
}

.status-icon.success {
  color: #67c23a;
}

.status-icon.danger {
  color: #f56c6c;
}

.status-text h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #333;
}

.status-text p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.order-actions {
  display: flex;
  gap: 15px;
}

/* 信息卡片 */
.info-card {
  background: white;
  padding: 25px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.info-card h3 {
  margin: 0 0 20px 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
  border-bottom: 1px solid #e0e0e0;
  padding-bottom: 10px;
}

/* 地址信息 */
.address-info {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.address-item {
  display: flex;
  align-items: center;
}

.address-item .label {
  width: 80px;
  color: #666;
  font-weight: 500;
}

/* 商品列表 */
.goods-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.goods-item {
  display: flex;
  align-items: center;
  padding: 20px 0;
  border-bottom: 1px solid #f0f0f0;
}

.goods-item:last-child {
  border-bottom: none;
}

.goods-image {
  width: 100px;
  height: 100px;
  margin-right: 20px;
  border-radius: 8px;
  overflow: hidden;
}

.goods-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.goods-info {
  flex: 1;
}

.goods-info h4 {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.goods-spec {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #666;
}

.goods-price {
  display: flex;
  align-items: center;
  gap: 10px;
}

.goods-price .price {
  font-size: 16px;
  font-weight: 600;
  color: #ff6900;
}

.goods-price .quantity {
  font-size: 14px;
  color: #666;
}

.goods-total {
  font-size: 18px;
  font-weight: 600;
  color: #ff6900;
}

/* 订单信息 */
.order-info {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.info-row {
  display: flex;
  align-items: center;
}

.info-row .label {
  width: 120px;
  color: #666;
  font-weight: 500;
}

/* 费用明细 */
.amount-detail {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.amount-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
}

.amount-row.total {
  border-top: 1px solid #e0e0e0;
  padding-top: 15px;
  margin-top: 10px;
  font-size: 16px;
  font-weight: 600;
}

.discount {
  color: #67c23a;
}

.total-amount {
  color: #ff6900;
  font-size: 20px;
}

/* 订单不存在 */
.order-not-found {
  background: white;
  padding: 60px 20px;
  border-radius: 8px;
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .container {
    padding: 15px;
  }

  .order-status-card {
    flex-direction: column;
    align-items: flex-start;
    gap: 20px;
  }

  .status-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .order-actions {
    width: 100%;
    justify-content: center;
  }

  .goods-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .goods-image {
    align-self: center;
  }

  .goods-total {
    align-self: flex-end;
  }

  .address-item,
  .info-row {
    flex-direction: column;
    align-items: flex-start;
    gap: 5px;
  }

  .address-item .label,
  .info-row .label {
    width: auto;
  }
}
</style>
